package com.example.socketdemo.socket;

import cn.hutool.core.util.CharsetUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
public class VertxTcpServe extends AbstractVerticle {


    private final static Map<String, NetSocket> LOCAL_MAP = Maps.newHashMap();


    @Override
    public void start() throws Exception {
        NetServer server = vertx.createNetServer();
        server.connectHandler(socket -> {

            String handlerID = socket.writeHandlerID();
            System.out.println("服务端id" + handlerID);
            LOCAL_MAP.put(handlerID, socket);
            // 接收消息
            socket.handler(buffer -> {
                System.out.println(buffer.toString(CharsetUtil.CHARSET_GBK));
            }).closeHandler(close -> {
                LOCAL_MAP.remove(handlerID);
                log.info("客户端断开连接" + socket.writeHandlerID());
            });



        }).listen(10123, "192.168.2.141", res -> {
            if (res.succeeded()) {
                log.info("tcpServer 启动成功====");
            } else {
                log.info("tcpServer 启动失败====  {}", res.cause().getMessage());
            }
        });

        // 模拟全局推送消息 30秒后
        vertx.setPeriodic(5000, timer -> {
            System.out.println("时间到了， map size " + LOCAL_MAP.size());
            LOCAL_MAP.forEach((k, v) -> {
                System.out.println("定时任务触发");
                System.out.println("id: " + k);
                v.write(Buffer.buffer("TcpServer Receive -=== Hello Vertx from Server!"));
            });
        });
    }


    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxTcpServe());
    }
}
